﻿using Peter;
using SmallTool.BaseFile;
using SmallTool.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmallTool.frm
{
    public partial class frm_Select : Form
    {
        public frm_Select()
        {
            InitializeComponent();
        }

        private void frm_Select_Load(object sender, EventArgs e)
        {
            ResetCBDataSource();
        }

        private void frm_Select_Resize(object sender, EventArgs e)
        {
            WidthChange();
        }

        private void WidthChange()
        {
            // 获取窗体的宽
            int _width = this.groupBox2.Width;
            sc_3.SplitterDistance = (_width - 100) / 2 - 7;
            sc_4.SplitterDistance = 100;
        }

        private void btn_reset_Click(object sender, EventArgs e)
        {
            ResetCBDataSource();
        }

        private void ResetCBDataSource()
        {
            cb_befor.DataSource = null;
            cb_after.DataSource = null;
            // 初始化数据库下拉框
            List<string> dtList = BaseCS.instance.GetDataTable();
            cb_befor.DataSource = dtList.ToArray();
            cb_after.DataSource = dtList.ToArray();
        }

        private void btn_selectSql_Click(object sender, EventArgs e)
        {
            frm_sqlList frm = new frm_sqlList();
            frm.Owner = this;
            frm.ShowDialog();
            txt_sql.Text = frm.SelectSQL;
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            txt_sql.Text = string.Empty;
        }

        private void btn_create_Click(object sender, EventArgs e)
        {
            lv_befor.Items.Clear();
            lv_after.Items.Clear();

            string selectSQL = txt_sql.Text.Trim();
            if (string.IsNullOrWhiteSpace(selectSQL))
            {
                MessageBox.Show("请选择要查询的语句");
                return;
            }
            string[] arr = selectSQL.Split(',');
            string beforDataBase = cb_befor.Text.Trim();
            string afterDataBase = cb_after.Text.Trim();
            if (string.IsNullOrWhiteSpace(beforDataBase) || string.IsNullOrWhiteSpace(afterDataBase))
            {
                MessageBox.Show("请选择相关的数据库");
                return;
            }


            DataBaseConnectModel connectModel = BaseCS.instance.GetOpenModel();
            if (connectModel != null)
            {
                string savePath = BaseCS.instance.GetSavePath(1);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string beforFileName = "{0}更新前.txt";
                string saveBeforFileName = string.Empty;
                string afterFileName = "{0}更新后.txt";
                string saveAfterFileName = string.Empty;
                string conStrBefor = string.Format("Server={0};Database={1};Uid={2};Pwd={3};", connectModel.IP, beforDataBase, connectModel.LoginName, connectModel.PassWord);
                string conStrAfter = string.Format("Server={0};Database={1};Uid={2};Pwd={3};", connectModel.IP, afterDataBase, connectModel.LoginName, connectModel.PassWord);
                foreach (var item in arr)
                {
                    saveBeforFileName = string.Format(beforFileName, item);
                    saveAfterFileName = string.Format(afterFileName, item);
                    SelectSQLModel selectModel = BaseCS.instance.GetModelSelectSQL(item);
                    if (selectModel == null) continue;
                    string sql = selectModel.SelectSQL;
                    if (string.IsNullOrWhiteSpace(sql)) continue;
                    StringBuilder sbBefor = new StringBuilder();
                    StringBuilder sbAfter = new StringBuilder();
                    try
                    {
                        using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(conStrBefor, sql))
                        {
                            while (sdr.Read())
                            {
                                if (!string.IsNullOrWhiteSpace(sbBefor.ToString())) sbBefor.AppendLine();
                                for (int i = 0; i < sdr.FieldCount; i++)
                                {
                                    if (i > 0) sbBefor.Append("	");
                                    sbBefor.Append(sdr[i].ToString());
                                }
                            }

                            FileStream fs = new FileStream(savePath + @"\" + saveBeforFileName, FileMode.Create);
                            StreamWriter sw = new StreamWriter(fs);
                            sw.Write(sbBefor.ToString());
                            sw.Flush();
                            sw.Close();
                            fs.Close();

                            lv_befor.Items.Add(new ListViewItem(new string[] { saveBeforFileName, savePath + @"\" + saveBeforFileName }));
                        }
                        using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(conStrAfter, sql))
                        {
                            while (sdr.Read())
                            {
                                if (!string.IsNullOrWhiteSpace(sbAfter.ToString())) sbAfter.AppendLine();
                                for (int i = 0; i < sdr.FieldCount; i++)
                                {
                                    if (i > 0) sbAfter.Append("	");
                                    sbAfter.Append(sdr[i].ToString());
                                }
                            }

                            FileStream fs = new FileStream(savePath + @"\" + saveAfterFileName, FileMode.Create);
                            StreamWriter sw = new StreamWriter(fs);
                            sw.Write(sbAfter.ToString());
                            sw.Flush();
                            sw.Close();
                            fs.Close();

                            lv_after.Items.Add(new ListViewItem(new string[] { saveAfterFileName, savePath + @"\" + saveAfterFileName }));
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void btn_comparison_Click(object sender, EventArgs e)
        {
            if (lv_befor.SelectedItems.Count <= 0)
            {
                MessageBox.Show("请选择要对比的文件");
                return;
            }
            try
            {
                // 获取选中的两个文件
                string beforFile = lv_befor.SelectedItems[0].SubItems[1].Text;
                int index = lv_befor.SelectedIndices[0];
                string afterFile = lv_after.Items[index].SubItems[1].Text;
                if (string.IsNullOrWhiteSpace(beforFile) || string.IsNullOrWhiteSpace(afterFile))
                {
                    MessageBox.Show("请选择要对比的文件");
                    return;
                }
                string bc3 = BaseCS.instance.GetSavePath(2);
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = Path.GetFileName(bc3);
                info.Arguments = string.Format("{0} {1}", beforFile, afterFile);
                info.WorkingDirectory = Path.GetDirectoryName(bc3);
                info.CreateNoWindow = true;
                info.WindowStyle = ProcessWindowStyle.Normal;
                Process.Start(info);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
